<?php

namespace app\admin\controller\user;

use app\admin\model\Area;
use app\admin\model\Userbalance;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username';
    protected $noNeedRight = ['balance','score'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['group','ref'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->username);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;

                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                $db = array();

                $mobile = $params['ref_mobile'];
                if($mobile != ''){
                    $user = $this->model->where('mobile', $mobile)->find();
                    if(!$user) {
                        $this->error('推荐人不存在');
                    }
                    $db['ref_uid'] = $user['id'];
                }

                $dbUser = $this->model->where('id',$params['id'])->find();
                $password = $params['password'];
                if($password != ''){
                    $db['password'] =  md5(md5($password) . $dbUser['salt']);;
                }

                $db['username'] = $params['username'];
                $db['group_id'] = $params['group_id'];
                $db['avatar'] = $params['avatar'];
                $db['status'] = $params['status'];

                $this->model->where('id',$params['id'])->update($db);


                $this->success();

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $ref_uid = $row['ref_uid'];
        $refUser = $this->model->get($ref_uid);
        $row['ref_mobile'] = $refUser['mobile'];
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function balance($ids = ""){

        $userBalanceModel = new Userbalance();
        $in = $userBalanceModel->where('user_id',$ids)->where('type','in')->sum('amount');
        $out = $userBalanceModel->where('user_id',$ids)->where('type','out')->sum('amount');

        $bal = $in-$out;
        $bal = formatMoney($bal);
        $this->success("","",$bal);
    }

    public function score($ids = ""){

        $userScoreModel = new \app\admin\model\Userscore();
        $in = $userScoreModel->where('user_id',$ids)->where('type','in')->sum('score');
        $out = $userScoreModel->where('user_id',$ids)->where('type','out')->sum('score');

        $bal =$in-$out;
        $this->success($bal);
    }




}
